package com.example.musicplayer.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.example.musicplayer.R;
import com.example.musicplayer.commonUtils.ToastUtil;
import com.example.musicplayer.dialogTools.AddMusicDialog;
import com.example.musicplayer.dialogTools.NormalAlertDialog;
import com.example.musicplayer.musicTools.MusicListType;
import com.example.musicplayer.musicTools.MusicOp;
import com.example.musicplayer.musicTools.MusicSortType;
import com.example.musicplayer.musicClass.MusicInfo;
import com.example.musicplayer.musicClass.MusicMenu;
import com.example.musicplayer.service.MusicService;
import com.example.musicplayer.view.MusicSimpleDisplay;
import com.example.musicplayer.view.NewScrollView;
import com.example.musicplayer.view.SimpleDisplayView;
import com.example.musicplayer.viewTools.AdjustViewOrder;
import com.example.musicplayer.windowTools.WindowTools;

import java.util.ArrayList;
import java.util.List;

public class MusicListManageActivity extends BaseActivity {
    public static final String TAG = "MusicListManageActivity";
    public static final String TAG_ARRAY = "arrayAddTo";
    public static final int RESULT_CODE = 100;
    private TextView mTextViewSelect;
    private LinearLayout mMusicContainer;
    private LinearLayout mAdjustOrderArea;
    private Button mButtonAddTo;
    private Button mButtonDownload;
    private Button mButtonDelete;
    private Button mButtonSet;
    private List<MusicInfo> mMusic = new ArrayList<MusicInfo>();
    private final List<MusicSimpleDisplay> mDisplay = new ArrayList<MusicSimpleDisplay>();
    private boolean mStateChanged = false;
    private boolean mNeedUpdate = true;
    private MusicListType mMusicListType;
    private String mMusicMenuName;
    private MusicSortType mMusicSortType;
    //按下调整顺序按键时的y坐标
    private float mStartY;
    //调整顺序按下的view的编号
    private int mTargetNumber;
    //调整顺序的管理类
    private AdjustViewOrder mAdjustViewOrder;
    private MusicService.MusicBinder mMusicBinder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_list_manage);
        if ((mMusicBinder = getMusicServiceBinder()) == null) {
            finish();
        }
        WindowTools.lightStatusBar(getWindow());

        initView();
        addListener();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus && mNeedUpdate) {
            initMusicList();
            for (int i = 0; i < mMusic.size(); i++)
                addNewMusicView(i + 1);
            updateMusicView();
            updateView();
            mNeedUpdate = false;
        }
    }

    @Override
    public void onBackPressed() {
        finishActivity();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        Log.d(TAG, "onActivityResult(): requestCode is " + requestCode + ", resultCode is " + resultCode);
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == MusicMenuManageActivity.RESULT_CODE && data != null) {
            if (data.getBooleanExtra("result", false)) {
                Bundle bundle = data.getExtras();
                if (bundle != null) {
                    String[] musicMenuName = bundle.getStringArray(TAG_ARRAY);
                    if (musicMenuName != null)
                        addSelectedMusicToMusicMenu(musicMenuName);
                }
            }
        }
    }

    private void initView() {
        mTextViewSelect = findViewById(R.id.button_music_list_manage_select);
        mMusicContainer = findViewById(R.id.linear_layout_music_container);
        mAdjustOrderArea = findViewById(R.id.linear_layout_adjust_music_order);
        mButtonAddTo = findViewById(R.id.button_add_to);
        mButtonDownload = findViewById(R.id.button_download);
        mButtonDelete = findViewById(R.id.button_delete);
        mButtonSet = findViewById(R.id.button_set_background_music);
    }

    @SuppressLint("ClickableViewAccessibility")
    private void addListener() {
        mTextViewSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doClickSelect();
            }
        });
        findViewById(R.id.button_music_list_manage_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doClickClose();
            }
        });
        findViewById(R.id.button_music_list_manage_down).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doClickDown();
            }
        });
        findViewById(R.id.linear_layout_add_to).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doClickAddTo();
            }
        });
        mButtonAddTo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doClickAddTo();
            }
        });
        findViewById(R.id.linear_layout_download).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doClickDownload();
            }
        });
        mButtonDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doClickDownload();
            }
        });
        findViewById(R.id.linear_layout_delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doClickDelete();
            }
        });
        mButtonDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doClickDelete();
            }
        });
        findViewById(R.id.linear_layout_set_background_music).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doClickSetBackgroundMusic();
            }
        });
        mButtonSet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doClickSetBackgroundMusic();
            }
        });
        mAdjustOrderArea.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                float y = event.getY();
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mStartY = y;
                        break;
                    case MotionEvent.ACTION_MOVE:
                        mAdjustViewOrder.adjustView(mStartY, y, true);
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        //获取结束时的位置
                        int endNumber = mAdjustViewOrder.adjustView(mStartY, y, false);
                        musicMenuMusicOrderChanged(endNumber);
                        startAdjustOrder(false);
                        break;
                }
                return false;
            }
        });
    }

    @SuppressLint("ClickableViewAccessibility")
    private void addListener(final MusicSimpleDisplay display) {
        display.getView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                display.setSelected(!display.getSelected());
                updateView();
            }
        });
        display.getImageViewAdjust().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        display.getImageViewAdjust().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    if (mDisplay.size() > 1) {
                        //获取按下时的item编号
                        mTargetNumber = getDisplayNumber(display);
                        startAdjustOrder(true);
                        mAdjustViewOrder = new AdjustViewOrder(new ArrayList<SimpleDisplayView>(mDisplay),
                                mTargetNumber, mAdjustOrderArea.getHeight());
                    }
                }
                return false;
            }
        });
    }

    //初始化歌曲列表类型
    private void initMusicList() {
        Intent intent = getIntent();
        MusicListType type = (MusicListType) intent.getSerializableExtra("musicListType");
        mMusicMenuName = intent.getStringExtra("musicMenuName");
        if (type == null) {
            mMusicListType = MusicListType.TYPE_LOCAL;
        } else {
            mMusicListType = type;
        }
        updateMusic();
    }

    //更新列表的音乐
    private void updateMusic() {
        if (mMusicListType == MusicListType.TYPE_FAVORITE) {
            List<MusicInfo> list = MusicInfo.getLocalMusic();
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getFavorite() == 1) {
                    mMusic.add(list.get(i));
                }
            }
        } else if (mMusicListType == MusicListType.TYPE_MENU) {
            MusicMenu musicMenu = MusicInfo.getMusicMenuByName(mMusicMenuName);
            if (musicMenu != null) {
                mMusicSortType = musicMenu.getMusicSortType();
                List<Integer> musicId = MusicOp.sort(mMusicMenuName);
                for (int i = 0; i < musicId.size(); i++) {
                    mMusic.add(MusicInfo.getMusicInfoById(musicId.get(i)));
                }
            }
        } else {
            mMusic = MusicInfo.getLocalMusic();
        }
    }

    //删除选定的歌曲
    private void deleteMusic() {
        if (mMusicListType != MusicListType.TYPE_FAVORITE && mMusicListType != MusicListType.TYPE_MENU) {
            return;
        }
        if (mMusicBinder == null) {
            return;
        }
        List<MusicInfo> deleteMusicList = new ArrayList<MusicInfo>();
        for (int i = 0; i < mDisplay.size(); i++) {
            if (mDisplay.get(i).getSelected()) {
                deleteMusicList.add(mDisplay.get(i).getMusicInfo());
                mDisplay.remove(i);
                mMusicContainer.removeViewAt(i);
                i--;
            }
        }
        //若删除了歌曲，则操作状态置为true
        if (deleteMusicList.size() > 0)
            mStateChanged = true;
        //判断列表类型并删除音乐
        if (mMusicListType == MusicListType.TYPE_FAVORITE) {
            for (int i = 0; i < deleteMusicList.size(); i++) {
                mMusicBinder.changeMusicFavorite(deleteMusicList.get(i));
            }
        }
        if (mMusicListType == MusicListType.TYPE_MENU) {
            MusicInfo.deleteMusicMenuInfo(MusicInfo.getMusicMenuByName(mMusicMenuName), deleteMusicList);
        }
        updateView();
    }

    //在末尾插入歌曲项视图
    private void addNewMusicView(int index) {
        int listType = mMusicSortType == null ? SimpleDisplayView.TYPE_CONFIRM : (mMusicSortType == MusicSortType.SORT_DEFAULT ?
                SimpleDisplayView.TYPE_SELECT : SimpleDisplayView.TYPE_CONFIRM);
        MusicSimpleDisplay display = new MusicSimpleDisplay(listType, index);
        mMusicContainer.addView(display.getView());
        mDisplay.add(display);
        addListener(display);
    }

    //更新歌曲列表项视图
    private void updateMusicView() {
        for (int i = 0; i < mMusic.size(); i++)
            mDisplay.get(i).update(mMusic.get(i));
    }

    //更新页面的显示内容
    private void updateView() {
        updateBottomTabState();
        updateToolbarState();
    }

    //更新底部栏状态
    private void updateBottomTabState() {
        boolean flag = false;
        for (int i = 0; i < mDisplay.size(); i++)
            if (mDisplay.get(i).getSelected()) {
                flag = true;
                break;
            }
        mButtonAddTo.setEnabled(flag);
        mButtonDownload.setEnabled(flag);
        mButtonSet.setEnabled(flag);
        findViewById(R.id.textview_add_to).setEnabled(flag);
        findViewById(R.id.textview_download).setEnabled(flag);
        findViewById(R.id.textview_set_background_music).setEnabled(flag);
        if (mMusicListType == MusicListType.TYPE_LOCAL || mMusicListType == MusicListType.TYPE_PURCHASED) {
            mButtonDelete.setEnabled(false);
            findViewById(R.id.textview_delete).setEnabled(false);
        } else {
            mButtonDelete.setEnabled(flag);
            findViewById(R.id.textview_delete).setEnabled(flag);
        }
    }

    //更新状态栏的显示
    private void updateToolbarState() {
        int selectedCounts = 0;
        for (int i = 0; i < mDisplay.size(); i++) {
            if (mDisplay.get(i).getSelected()) {
                selectedCounts++;
            }
        }
        if (selectedCounts == mDisplay.size()) {
            mTextViewSelect.setText(R.string.activity_music_list_manage_toolbar_not_select);
        } else {
            mTextViewSelect.setText(R.string.activity_music_list_manage_toolbar_select);
        }
        TextView toolbarTextView = findViewById(R.id.textview_music_list_manage_toolbar);
        if (selectedCounts == 0) {
            toolbarTextView.setText(R.string.activity_music_list_manage_toolbar);
        } else {
            String text = "已选定" + selectedCounts + "首";
            toolbarTextView.setText(text);
        }
    }

    //点击全选或者全不选
    private void doClickSelect() {
        boolean flag = false;
        if (mTextViewSelect.getText().toString().equals(getResources().getString(R.string.activity_music_list_manage_toolbar_select)))
            flag = true;
        for (int i = 0; i < mDisplay.size(); i++)
            mDisplay.get(i).setSelected(flag);
        updateView();
    }

    private void doClickClose() {
        finishActivity();
    }

    private void doClickDown() {
        NewScrollView scrollView = findViewById(R.id.scroll_view_music_list_manage);
        scrollView.smoothScrollTo(0, Integer.MAX_VALUE);
    }

    private void doClickAddTo() {
        if (mButtonAddTo.isEnabled()) {
            AddMusicDialog addMusicDialog = new AddMusicDialog(this);
            final Dialog dialog = addMusicDialog.getDialog();
            TextView textViewFavorite = addMusicDialog.getFavoriteMusic();
            TextView textViewMusicMenu = addMusicDialog.getMusicMenu();
            TextView textViewPlayList = addMusicDialog.getPlayList();
            TextView cancel = addMusicDialog.getCancel();
            cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            textViewFavorite.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    addSelectedMusicToFavorite();
                }
            });
            textViewMusicMenu.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    jumpToMusicMenuManageActivity();
                }
            });
            textViewPlayList.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    addSelectedMusicToPlayList();
                }
            });
            dialog.show();
        }
    }

    private void doClickDownload() {

    }

    //删除歌曲
    private void doClickDelete() {
        if (mButtonDelete.isEnabled()) {
            Context context = this;
            String title = context.getResources().getString(R.string.title_delete_music);
            String text = context.getResources().getString(R.string.text_delete_music);
            NormalAlertDialog normalAlertDialog = new NormalAlertDialog(context, title, text);
            final Dialog dialog = normalAlertDialog.getDialog();
            TextView cancel = normalAlertDialog.getCancel();
            TextView confirm = normalAlertDialog.getConfirm();
            cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            confirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    deleteMusic();
                    dialog.dismiss();
                }
            });
            dialog.show();
        }
    }

    private void doClickSetBackgroundMusic() {

    }

    //把选中的歌曲添加到我喜欢
    private void addSelectedMusicToFavorite() {
        if (mMusicBinder != null) {
            List<MusicInfo> musicList = new ArrayList<MusicInfo>();
            for (int i = 0; i < mDisplay.size(); i++) {
                if (mDisplay.get(i).getSelected()) {
                    musicList.add(mDisplay.get(i).getMusicInfo());
                }
            }
            //判断音乐是否正在播放
            for (int i = 0; i < musicList.size(); i++) {
                if (musicList.get(i).getId() == mMusicBinder.getId())
                    mMusicBinder.changeToFavorite();
                else
                    MusicInfo.changeToFavorite(musicList.get(i));
            }
        }
    }

    //把选中的歌曲加到歌单中
    private void addSelectedMusicToMusicMenu(String[] musicMenuName) {
        if (musicMenuName != null && musicMenuName.length > 0) {
            mStateChanged = true;
            List<MusicInfo> musicList = new ArrayList<MusicInfo>();
            for (int i = 0; i < mDisplay.size(); i++) {
                if (mDisplay.get(i).getSelected()) {
                    musicList.add(mDisplay.get(i).getMusicInfo());
                }
            }
            //歌曲插入歌单中
            for (String s : musicMenuName) {
                MusicMenu musicMenu = MusicInfo.getMusicMenuByName(s);
                MusicInfo.insertMusicMenuInfo(musicMenu, musicList);
            }
        }
    }

    //将选中的歌曲加到播放列表中
    private void addSelectedMusicToPlayList() {
        if (mMusicBinder != null) {
            List<MusicInfo> musicList = new ArrayList<MusicInfo>();
            for (int i = 0; i < mDisplay.size(); i++) {
                if (mDisplay.get(i).getSelected()) {
                    musicList.add(mDisplay.get(i).getMusicInfo());
                }
            }
            //判断音乐是否包含在本地音乐中
            for (int i = 0; i < musicList.size(); i++) {
                if (!MusicInfo.has(musicList.get(i))) {
                    musicList.remove(i);
                    i--;
                }
            }
            if (musicList.size() > 0) {
                mMusicBinder.addToPlayList(musicList);
            }
        }
    }

    //处理歌单的歌曲默认顺序发生改变
    private void musicMenuMusicOrderChanged(int endNumber) {
        if (mTargetNumber != endNumber) {
            //状态改变
            mStateChanged = true;
            List<Integer> musicId = new ArrayList<Integer>();
            List<Integer> musicOrder = new ArrayList<Integer>();
            //获取调整后的顺序信息
            if (mTargetNumber > endNumber) {
                for (int i = endNumber; i < mTargetNumber; i++) {
                    musicId.add(mDisplay.get(i).getMusicInfo().getId());
                    musicOrder.add(i + 1);
                }
            } else {
                for (int i = endNumber; i > mTargetNumber; i--) {
                    musicId.add(mDisplay.get(i).getMusicInfo().getId());
                    musicOrder.add(i - 1);
                }
            }
            musicId.add(mDisplay.get(mTargetNumber).getMusicInfo().getId());
            musicOrder.add(endNumber);
            MusicMenu temp = MusicInfo.getMusicMenuByName(mMusicMenuName);
            if (temp != null)
                temp.changeMusicOrder(musicId, musicOrder);
            //调整歌曲项的位置
            MusicSimpleDisplay display = mDisplay.get(mTargetNumber);
            mDisplay.remove(mTargetNumber);
            mMusicContainer.removeViewAt(mTargetNumber);
            mDisplay.add(endNumber, display);
            mMusicContainer.addView(display.getView(), endNumber);
        }
    }

    //进入或离开调整顺序模式的处理
    private void startAdjustOrder(boolean isAdjust) {
        NewScrollView scrollView = findViewById(R.id.scroll_view_music_list_manage);
        //设置scrollview是否能滑动
        scrollView.setCanScroll(!isAdjust);
        mAdjustOrderArea.setClickable(isAdjust);
        int alpha = isAdjust ? 0 : 255;
        for (int i = 0; i < mDisplay.size(); i++) {
            //设置视图项透明
            mDisplay.get(i).setBackgroundAlpha(alpha);
            mDisplay.get(i).getView().setClickable(!isAdjust);
            mDisplay.get(i).getImageViewAdjust().setClickable(!isAdjust);
        }
    }

    //当前视图的编号
    private int getDisplayNumber(MusicSimpleDisplay display) {
        for (int i = 0; i < mDisplay.size(); i++)
            if (mDisplay.get(i) == display)
                return i;
        return 0;
    }

    //跳转选择歌单
    private void jumpToMusicMenuManageActivity() {
        if (MusicInfo.getMusicMenuCounts() > 0) {
            Intent intent = new Intent(this, MusicMenuManageActivity.class);
            MusicMenu musicMenu = MusicInfo.getMusicMenuByName(mMusicMenuName);
            if (musicMenu != null) {
                intent.putExtra(MusicMenuManageActivity.DEFAULT_SELECTED, musicMenu.getOrder());
            }
            intent.putExtra(MusicMenuManageActivity.CONFIRM_CODE, TAG);
            startActivityForResult(intent, 1);
            setPendingTransition(R.anim.activity_vertical_enter, R.anim.fake_anim);
        }
    }

    private void finishActivity() {
        Intent intent = new Intent();
        intent.putExtra("result", mStateChanged);
        this.setResult(RESULT_CODE, intent);
        finish();
        setPendingTransition(R.anim.fake_anim, R.anim.activity_vertical_exit);
    }
}